package com.frame.service.common.impl;

import com.frame.common.RespEnum;
import com.frame.common.constant.RedisConstant;
import com.frame.common.exception.ServerException;
import com.frame.model.user.req.ReqRefreshTokenVo;
import com.frame.model.user.res.ResRefreshTokenVo;
import com.frame.redis.StringRedisUtil;
import com.frame.service.common.UserCommonService;
import com.frame.token.TokenUitl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Flying
 * @Description
 * @date 13:29 2018-08-24
 **/
@Service
@PropertySource(value = "classpath:common-service.properties")
public class UserCommonServiceImpl implements UserCommonService {

    @Autowired
    private StringRedisUtil redisUtil;


    /**
     * 刷新token
     *
     * @param reqRefreshTokenVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResRefreshTokenVo refreshToken(ReqRefreshTokenVo reqRefreshTokenVo) {
        String  userId = redisUtil.get(RedisConstant.USER_REFRESH_TOKEN+ reqRefreshTokenVo.getRefreshToken());
        if(userId==null){
            throw new ServerException(RespEnum.LONG_TERM_USER_NOT_LOGGED_IN);
        }
        return this.createToken(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResRefreshTokenVo createToken(String userId){

        String accessTokenOld = redisUtil.get(RedisConstant.USER_ACCESS_RECORD_TOKEN+userId);
        String refreshTokenOld = redisUtil.get(RedisConstant.USER_REFRESH_RECORD_TOKEN+userId);
        if(refreshTokenOld != null){
            redisUtil.del(RedisConstant.USER_REFRESH_TOKEN+refreshTokenOld);
        }
        if(accessTokenOld != null){
            redisUtil.del(RedisConstant.USER_ACCESS_TOKEN+accessTokenOld);
        }
        redisUtil.del(RedisConstant.USER_ACCESS_RECORD_TOKEN+userId);
        redisUtil.del(RedisConstant.USER_REFRESH_RECORD_TOKEN+userId);

        ResRefreshTokenVo resRefreshTokenVo = new ResRefreshTokenVo();
        resRefreshTokenVo.setAccessToken(TokenUitl.getToken());
        resRefreshTokenVo.setRefreshToken(TokenUitl.getToken());

        redisUtil.set(RedisConstant.USER_ACCESS_RECORD_TOKEN+userId, resRefreshTokenVo.getAccessToken(),60 * 60 * 24);
        redisUtil.set(RedisConstant.USER_ACCESS_TOKEN+ resRefreshTokenVo.getAccessToken(),userId ,60 * 60 * 24);

        redisUtil.set(RedisConstant.USER_REFRESH_RECORD_TOKEN+userId, resRefreshTokenVo.getRefreshToken(),60 * 60 * 48);
        redisUtil.set(RedisConstant.USER_REFRESH_TOKEN+ resRefreshTokenVo.getRefreshToken(),userId,60 * 60 * 48);
        return resRefreshTokenVo;
    }








}
